package net.orange.architecture.validator;

import java.util.Map;

import net.orange.architecture.model.BaseValueObject;
import net.orange.architecture.process.IBaseProcess;
import net.orange.architecture.process.ProcessFactory;

import org.apache.commons.beanutils.BeanUtils;

/**
 * Validation : The object can't be duplicate.
 */
public class NotDulicateValidator extends ObjectValidator implements
		IObjectValidator {

	/**
	 * The target value object.
	 */
	private BaseValueObject target;	
	/**
	 * The field name.
	 */
	private String fieldName;	
	/**
	 * The field alias.
	 */
	private String fieldAlias;


	/**
	 * Disabled the default contractor.
	 */
	@SuppressWarnings("unused")
	private NotDulicateValidator() {

	}

	/**
	 * Constructor with target, field name , field alias and DAO object..
	 * 
	 * @param target The target object.
	 * @param fieldName The field name for the code.
	 * @param fieldAlias The code field alias 
	 */
	public NotDulicateValidator(BaseValueObject target, String fieldName,
			String fieldAlias) {
		this.target = target;
		this.fieldName = fieldName;
		this.fieldAlias = fieldAlias;
	}

	/* (non-Javadoc)
	 * @see net.orange.architecture.validator.ObjectValidator#check()
	 */
	public boolean check() throws Exception {
		Map map = BeanUtils.describe(target);
		String fieldValue = (String) map.get(fieldName);
		
		IBaseProcess process =  ProcessFactory.get(target.getClass());
		
		BaseValueObject other = process.find(fieldName, fieldValue);
		
		return (other == null || other.getPk() == target.getPk());
	}
	/* (non-Javadoc)
	 * @see net.orange.architecture.validator.ObjectValidator#getMessage()
	 */
	public String getMessage() {
		return "The " + fieldAlias + " has existed";
	}
	
}